import json
from time import sleep

import synonyms
import jieba
from RedisClient import RedisClient
from config.secure import MAIN_DB
from models.base import db as samereportDB
from models.sentence import sentences
from models.sentence_word import SentenceWord


class SuggestGenerator(object):
    db = samereportDB
    r = RedisClient(MAIN_DB)

    def suggest(self, data):
        order_number = data.split('#')[0]
        sentence_index = data.split('#')[1]
        sentence = data.split('#')[2]
        str_words_list = jieba.lcut(sentence)
        str_words = []
        similarWords = []
        for words in str_words_list:
            if len(words) >= 2:
                str_words.append(words)
        for i in str_words:
            res = synonyms.nearby(i)[0]
            if len(res) > 1:
                similarWords.append(res)
        suggest = []
        for item in similarWords:
            info = {
                'word': item[0],
                'suggest': '  '.join(item[1:])
            }
            suggest.append(info)
        jsonStr = json.dumps(suggest).encode("utf-8").decode("unicode_escape")
        try:
            if order_number[0] == '9':
                self.db.session.query(sentences).filter_by(order_number=order_number).filter_by(
                    sentence_index=sentence_index).update({
                    'suggest': jsonStr
                })
            else:
                self.db.session.query(SentenceWord).filter_by(order_number=order_number).filter_by(
                    sentence_index=sentence_index).update({
                    'suggest': jsonStr
                })
            self.db.session.commit()
            self.db.session.close()
        except Exception as e:
            print(e)
            self.db.session.close()


if __name__ == '__main__':
    bot = SuggestGenerator()
    while True:
        sentence_data = bot.r.get_suggest_sentence()
        if sentence_data:
            bot.suggest(sentence_data)
        else:
            sleep(1)
